import 'package:flutter/material.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/evaluationSkillProgressResult.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

import '../../themes/pageStyles.dart';

class EvaluationProficiencySkillProgressDataGrid extends StatefulWidget {
  EvaluationProficiencySkillProgressDataGrid(
      {Key? key,
      required this.level,
      required this.skillId,
      required this.skillTitle})
      : super(key: key);
  final String skillId;
  final String level;
  final String skillTitle;

  @override
  State<EvaluationProficiencySkillProgressDataGrid> createState() =>
      _EvaluationProficiencySkillProgressDataGridState();
}

class _EvaluationProficiencySkillProgressDataGridState
    extends State<EvaluationProficiencySkillProgressDataGrid> {
  final box = Hive.box('appconfig');
  final EvaluationController controller = Get.find();

  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  bool isSchoolAdmin = true;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();
  List<SkillProgressItem> skillProgressItems = [];

  @override
  void initState() {
    String _classId = box.get(CacheManagerKey['currentclass'].toString()) ?? '';
    Future.delayed(Duration(milliseconds: 200), () {
      if (_classId != '') {
        controller.fetchEvaluationProficiencySkillProgressData(
            _classId, widget.level, widget.skillId);
      }
    });
    super.initState();
  }

  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build evaluation proficiency skill progress datagrid');

    return Scaffold(
      //backgroundColor: Colors.transparent,
      appBar: CustomAppBar(title: this.widget.skillTitle),
      body: Container(
        decoration: _pageStyles.pageBoxDecoration(),
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 12.0, vertical: 30.0),
          decoration: _pageStyles.dataGridBackground(),
          child: Container(
            margin: EdgeInsets.all(12.0),
            decoration: _pageStyles.dataGridForground(),
            child: controller.obx(
              (data) {
                if (controller.evaluationProficiencySkillProgressData.length >
                    0) {
                  skillProgressItems =
                      controller.evaluationProficiencySkillProgressData;
                  return _buildDataGrid();
                } else {
                  return Visibility(
                    child: Text(''),
                    visible: false,
                  );
                }
              },
              // //onEmpty: Text('Data not available ...'.tr),
              // onLoading: Center(
              //     child: CircularProgressIndicator(
              //   backgroundColor: Get.theme.primaryColorDark,
              //   strokeWidth: 9.0,
              // )),
            ),
          ),
        ),
      ),
    );
  }

  SfDataGrid _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;
    return SfDataGrid(
      source: SkillProgressDataGridSource(items: skillProgressItems),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      showCheckboxColumn: false,
      rowsPerPage: 15,
      allowSorting: true,
      allowTriStateSorting: true,
      selectionMode: SelectionMode.single,
      navigationMode: GridNavigationMode.row,
      controller: _dataGridController,
      columns: <GridColumn>[
        GridColumn(
          columnName: 'FirstName',
          width: isWebOrDesktop ? 180 : 180,
          label: buildDataGridColumnLabel('FirstName'),
        ),
        GridColumn(
          width: 180,
          columnName: 'LastName',
          label: buildDataGridColumnLabel('LastName'),
        ),
        GridColumn(
          columnName: 'Progress',
          width: 480,
          label: buildDataGridColumnLabel('Progress'),
        ),
        GridColumn(
          columnName: 'UserName',
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('UserName'),
        ),
      ],
    );
  }
}

class SkillProgressDataGridSource extends DataGridSource {
  SkillProgressDataGridSource({required List<SkillProgressItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<double>(
                  columnName: 'Progress',
                  value:
                      dataGridRow.progress! * 100 / dataGridRow.total!.toInt()),
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Progress') {
            double process = dataGridCell.value ?? 0;
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: LinearPercentIndicator(
                animation: true,
                lineHeight: 18.0,
                animationDuration: 1000,
                percent: process.toDouble() / 100,
                center: Text(
                  "${process.toStringAsFixed(2)}%",
                  style: TextStyle(color: Colors.black),
                ),
                progressColor: Get.theme.primaryColor,
                barRadius: Radius.circular(16),
                backgroundColor: AppTheme.colors.disableBtnLight,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
